<?php

namespace app\models\business;

use think\facade\Validate;
use think\Model;
use think\facade\Db;

class FileLogModel extends Model
{
    protected $connection = 'mongodb';
    protected $table = 'bu_file_log';

    const STATUS_NORMAL = 1;
    const STATUS_DELETE = 2;

    public function createRecord(array $param = [])
    {
        $checkRes = $this->checkSaveData($param);
        if ($checkRes['status'] != STATUS_CODE_SUCCESS) {
            return $checkRes;
        }
        $data = $checkRes['data'];
        $data['create_time'] = date('Y-m-d H:i:s');
        $res = self::insert($data);
        if (!$res) {
            return funReturn(STATUS_CODE_INSIDEERROR, '保存失败');
        }
        return funReturn(STATUS_CODE_SUCCESS, 'success');
    }

    /**
     * 验证需要保存的数据
     * @param array $params
     * @return array
     * @date 2021-09-22 10:34
     */
    private function checkSaveData(array $params = [])
    {
        $rule = [
            'api_key' => 'require|regex:[0-9]{6}$',
            'file_path' => "require",
            'file_time' => 'require|dateFormat:Y-m-d H:i:s',
        ];
        $message = [
            'api_key.require' => 'api_key不能为空',
            'api_key.regex' => 'api_key格式不合法',
            'file_path.require' => '缺少file_path',
            'file_time.require' => '缺少file_time',
            'file_time.dateFormat' => 'file_time格式不合法',
        ];
        $validate = Validate::message($message)->rule($rule);
        if (!$validate->check($params)) {
            return funReturn(STATUS_CODE_DATAERROR, $validate->getError());
        }

        $data = [
            'api_key' => (string)$params['api_key'],
            'file_path' => $params['file_path'],
            'file_status' => self::STATUS_NORMAL,
            'file_time' => $params['file_time'],
            'is_temp' => $this->checkFileIsTemp($params['file_path']) ? 1 : 0
        ];
        return funReturn(STATUS_CODE_SUCCESS, 'success', $data);
    }

    /**
     * 验证是否是临时文件
     * @param $file
     * @return bool
     * @date 2021-09-22 10:57
     */
    private function checkFileIsTemp($file)
    {
        $fileArr = explode('.', $file);
        if (count($fileArr) < 2) {
            return true;
        }
        return false;
    }

}